document.addEventListener('DOMContentLoaded', () => {
    const canvas = document.getElementById('flowCanvas');
    const configPanel = document.getElementById('configPanel');
    const flowChart = new FlowChart(canvas);
    let currentNode = null;

    // 初始化拖拽功能
    initializeDragAndDrop();

    // 初始化配置面板
    // initializeConfigPanel();

    // 初始化画布控制按钮
    initializeCanvasControls();

    function initializeDragAndDrop() {
        const nodeItems = document.querySelectorAll('.node-item');
        const canvas = document.getElementById('flowCanvas');

        nodeItems.forEach(item => {
            item.addEventListener('dragstart', (e) => {
                console.log('开始拖拽节点:', item.querySelector('.node-title').textContent);
                // 必须设置数据，否则某些浏览器不会触发拖拽
                e.dataTransfer.setData('text/plain', item.dataset.nodeType);
                // 设置允许的效果为复制
                e.dataTransfer.effectAllowed = 'copy';
            });
        });

        canvas.addEventListener('dragover', (e) => {
            // 阻止默认行为以允许放置
            e.preventDefault();
            // 设置放置效果为复制
            e.dataTransfer.dropEffect = 'copy';
        });

        canvas.addEventListener('drop', (e) => {
            e.preventDefault();

            // 获取拖拽的节点类型
            const nodeType = e.dataTransfer.getData('text/plain');
            console.log('放置节点类型:', nodeType);

            if (!nodeType) {
                console.error('拖拽数据丢失，无法获取节点类型');
                return;
            }

            // 获取画布的边界和位置
            const rect = canvas.getBoundingClientRect();

            // 计算相对于画布的位置，考虑缩放和滚动
            const position = {
                x: (e.clientX - rect.left) / flowChart.zoomScale + canvas.scrollLeft,
                y: (e.clientY - rect.top) / flowChart.zoomScale + canvas.scrollTop
            };

            console.log('放置位置:', position);

            // 创建新节点
            const node = NodeFactory.createNode(nodeType, position);
            console.log('创建节点:', node);

            // 添加到流程图中
            const element = flowChart.addNode(node);

            // 添加点击事件以显示配置面板
            element.addEventListener('click', (e) => {
                e.stopPropagation();
                window.openNodeConfig(node);
            });
        });
    }

    function initializeConfigPanel() {
        const configPanel = document.getElementById('configPanel');
        const closeBtn = configPanel.querySelector('.close-btn');
        const saveBtn = configPanel.querySelector('.save-btn');
        const nodeName = document.getElementById('nodeName');
        const addInputParamBtn = document.getElementById('addInputParam');
        const addOutputParamBtn = document.getElementById('addOutputParam');
        const inputParamsContainer = document.getElementById('inputParams');
        const outputParamsContainer = document.getElementById('outputParams');

        // 新增的变量
        const modelSpecific = document.querySelector('.model-specific');
        const agentSpecific = document.querySelector('.agent-specific');
        const ifelseSpecific = document.querySelector('.ifelse-specific');
        const iteratorSpecific = document.querySelector('.iterator-specific');
        const codeSpecific = document.querySelector('.code-specific');
        const templateSpecific = document.querySelector('.template-specific');
        const httpSpecific = document.querySelector('.http-specific');
        const databaseSpecific = document.querySelector('.database-specific');

        closeBtn.addEventListener('click', () => {
            configPanel.style.display = 'none';
            currentNode = null;
        });

        saveBtn.addEventListener('click', () => {
            if (!currentNode) return;

            // 保存通用属性
            currentNode.updateName(nodeName.value);

            // 保存参数信息
            const inputParams = [];
            const outputParams = [];

            inputParamsContainer.querySelectorAll('.param-item').forEach(item => {
                const nameInput = item.querySelector('.param-name');
                const typeSelect = item.querySelector('.param-type');
                const reqCheckbox = item.querySelector('.param-required');

                inputParams.push({
                    name: nameInput.value,
                    type: typeSelect.value,
                    required: reqCheckbox.checked
                });
            });

            outputParamsContainer.querySelectorAll('.param-item').forEach(item => {
                const nameInput = item.querySelector('.param-name');
                const typeSelect = item.querySelector('.param-type');

                outputParams.push({
                    name: nameInput.value,
                    type: typeSelect.value
                });
            });

            currentNode.updateParams({
                input: inputParams,
                output: outputParams
            });

            // 保存特定类型节点的配置
            switch (currentNode.type) {
                case 'model':
                    const modelType = document.getElementById('modelType');
                    const modelPrompt = document.getElementById('modelPrompt');
                    const modelTemperature = document.getElementById('modelTemperature');

                    currentNode.modelType = modelType.value;
                    currentNode.updatePrompt(modelPrompt.value);
                    currentNode.temperature = parseFloat(modelTemperature.value);
                    break;

                case 'agent':
                    const agentPrompt = document.getElementById('agentPrompt');
                    const tools = [];

                    document.querySelectorAll('#agentTools .tool-item').forEach(item => {
                        const toolName = item.querySelector('.tool-name').value;
                        const toolDesc = item.querySelector('.tool-description').value;

                        tools.push({
                            name: toolName,
                            description: toolDesc
                        });
                    });

                    currentNode.agentPrompt = agentPrompt.value;
                    currentNode.tools = tools;
                    break;

                case 'ifelse':
                    const condition = document.getElementById('condition');
                    currentNode.condition = condition.value;
                    break;

                case 'iterator':
                    const iterationKey = document.getElementById('iterationKey');
                    const maxIterations = document.getElementById('maxIterations');

                    currentNode.iterationKey = iterationKey.value;
                    currentNode.maxIterations = parseInt(maxIterations.value);
                    break;

                case 'code':
                    const codeLanguage = document.getElementById('codeLanguage');
                    const codeEditor = document.getElementById('codeEditor');

                    currentNode.language = codeLanguage.value;
                    currentNode.code = codeEditor.value;
                    break;

                case 'template':
                    const templateEditor = document.getElementById('templateEditor');
                    currentNode.template = templateEditor.value;
                    break;

                case 'http':
                    const httpUrl = document.getElementById('httpUrl');
                    const httpMethod = document.getElementById('httpMethod');
                    const httpHeaders = document.getElementById('httpHeaders');
                    const httpBody = document.getElementById('httpBody');

                    currentNode.url = httpUrl.value;
                    currentNode.method = httpMethod.value;

                    try {
                        currentNode.headers = JSON.parse(httpHeaders.value || '{}');
                        currentNode.requestBody = JSON.parse(httpBody.value || '{}');
                    } catch (error) {
                        alert('HTTP请求头或请求体格式不正确');
                        return;
                    }
                    break;

                case 'database':
                    const connectionString = document.getElementById('connectionString');
                    const sqlQuery = document.getElementById('sqlQuery');

                    currentNode.connectionString = connectionString.value;
                    currentNode.query = sqlQuery.value;
                    break;
            }

            // 更新节点
            flowChart.updateNode(currentNode);

            // 关闭配置面板
            configPanel.style.display = 'none';
            currentNode = null;
        });

        addInputParamBtn.addEventListener('click', () => {
            const paramItem = createParamItem(true);
            inputParamsContainer.appendChild(paramItem);
        });

        addOutputParamBtn.addEventListener('click', () => {
            const paramItem = createParamItem(false);
            outputParamsContainer.appendChild(paramItem);
        });

        // 智能体节点的工具添加按钮
        const addAgentToolBtn = document.getElementById('addAgentTool');
        if (addAgentToolBtn) {
            addAgentToolBtn.addEventListener('click', () => {
                const toolItem = createToolItem();
                document.getElementById('agentTools').appendChild(toolItem);
            });
        }

        // 打开节点配置面板
        window.openNodeConfig = function (node) {
            currentNode = node;

            // 重置所有特定配置部分的显示状态
            modelSpecific.style.display = 'none';
            agentSpecific.style.display = 'none';
            ifelseSpecific.style.display = 'none';
            iteratorSpecific.style.display = 'none';
            codeSpecific.style.display = 'none';
            templateSpecific.style.display = 'none';
            httpSpecific.style.display = 'none';
            databaseSpecific.style.display = 'none';

            // 显示对应类型的配置部分
            switch (node.type) {
                case 'model':
                    modelSpecific.style.display = 'block';
                    document.getElementById('modelType').value = node.modelType;
                    document.getElementById('modelPrompt').value = node.prompt;
                    document.getElementById('modelTemperature').value = node.temperature;
                    break;

                case 'agent':
                    agentSpecific.style.display = 'block';
                    document.getElementById('agentPrompt').value = node.agentPrompt;

                    // 清空并重新填充工具列表
                    const agentTools = document.getElementById('agentTools');
                    agentTools.innerHTML = '';

                    if (node.tools && node.tools.length > 0) {
                        node.tools.forEach(tool => {
                            const toolItem = createToolItem(tool.name, tool.description);
                            agentTools.appendChild(toolItem);
                        });
                    }
                    break;

                case 'ifelse':
                    ifelseSpecific.style.display = 'block';
                    document.getElementById('condition').value = node.condition;
                    break;

                case 'iterator':
                    iteratorSpecific.style.display = 'block';
                    document.getElementById('iterationKey').value = node.iterationKey;
                    document.getElementById('maxIterations').value = node.maxIterations;
                    break;

                case 'code':
                    codeSpecific.style.display = 'block';
                    document.getElementById('codeLanguage').value = node.language;
                    document.getElementById('codeEditor').value = node.code;
                    break;

                case 'template':
                    templateSpecific.style.display = 'block';
                    document.getElementById('templateEditor').value = node.template;
                    break;

                case 'http':
                    httpSpecific.style.display = 'block';
                    document.getElementById('httpUrl').value = node.url;
                    document.getElementById('httpMethod').value = node.method;
                    document.getElementById('httpHeaders').value = JSON.stringify(node.headers || {}, null, 2);
                    document.getElementById('httpBody').value = JSON.stringify(node.requestBody || {}, null, 2);
                    break;

                case 'database':
                    databaseSpecific.style.display = 'block';
                    document.getElementById('connectionString').value = node.connectionString;
                    document.getElementById('sqlQuery').value = node.query;
                    break;
            }

            // 设置节点名称
            nodeName.value = node.name || node.getDefaultName();

            // 清空参数容器
            inputParamsContainer.innerHTML = '';
            outputParamsContainer.innerHTML = '';

            // 填充输入参数
            if (node.params.input && node.params.input.length > 0) {
                node.params.input.forEach(param => {
                    const paramItem = createParamItem(true, param.name, param.type, param.required);
                    inputParamsContainer.appendChild(paramItem);
                });
            }

            // 填充输出参数
            if (node.params.output && node.params.output.length > 0) {
                node.params.output.forEach(param => {
                    const paramItem = createParamItem(false, param.name, param.type);
                    outputParamsContainer.appendChild(paramItem);
                });
            }

            // 显示配置面板
            configPanel.style.display = 'block';
        };
    }

    function showConfigPanel(node) {
        currentNode = node;
        configPanel.classList.add('active');

        // 填充节点名称
        const nameInput = document.getElementById('nodeName');
        nameInput.value = node.name || node.getDefaultName();

        // 清空并填充输入参数
        const inputParamsContainer = document.getElementById('inputParams');
        inputParamsContainer.innerHTML = '';
        node.params.input.forEach(param => {
            addParamInput(inputParamsContainer, param);
        });

        // 清空并填充输出参数
        const outputParamsContainer = document.getElementById('outputParams');
        outputParamsContainer.innerHTML = '';
        node.params.output.forEach(param => {
            addParamInput(outputParamsContainer, param);
        });

        // 显示/隐藏模型特定字段
        const modelSpecific = document.querySelector('.model-specific');
        if (node.type === 'model') {
            modelSpecific.style.display = 'block';
            const promptInput = document.getElementById('modelPrompt');
            promptInput.value = node.prompt || '';

            // 设置模型类型和温度
            if (node.modelType) {
                document.getElementById('modelType').value = node.modelType;
            }

            if (node.temperature) {
                document.getElementById('modelTemperature').value = node.temperature;
            }
        } else {
            modelSpecific.style.display = 'none';
        }
    }

    function addParamInput(container, param = null) {
        const paramItem = document.createElement('div');
        paramItem.className = 'param-item';
        paramItem.innerHTML = `
            <input type="text" class="param-name" placeholder="参数名" value="${param ? param.name : ''}">
            <select class="param-type">
                <option value="String" ${param && param.type === 'String' ? 'selected' : ''}>String</option>
                <option value="Number" ${param && param.type === 'Number' ? 'selected' : ''}>Number</option>
                <option value="Boolean" ${param && param.type === 'Boolean' ? 'selected' : ''}>Boolean</option>
                <option value="Array" ${param && param.type === 'Array' ? 'selected' : ''}>Array</option>
                <option value="Object" ${param && param.type === 'Object' ? 'selected' : ''}>Object</option>
            </select>
            <div class="param-actions">
                <button class="remove-param"><i class="fas fa-trash"></i></button>
            </div>
        `;

        container.appendChild(paramItem);

        // 为删除按钮绑定事件
        const removeBtn = paramItem.querySelector('.remove-param');
        removeBtn.addEventListener('click', () => {
            container.removeChild(paramItem);
        });
    }

    // 创建参数项
    function createParamItem(isInput, name = '', type = 'string', required = false) {
        const paramItem = document.createElement('div');
        paramItem.className = 'param-item';

        const nameInput = document.createElement('input');
        nameInput.type = 'text';
        nameInput.className = 'form-control param-name';
        nameInput.placeholder = '参数名称';
        nameInput.value = name;

        const typeSelect = document.createElement('select');
        typeSelect.className = 'form-control param-type';

        const typeOptions = ['string', 'number', 'boolean', 'object', 'array'];
        typeOptions.forEach(option => {
            const optElement = document.createElement('option');
            optElement.value = option;
            optElement.textContent = option;
            if (option === type) {
                optElement.selected = true;
            }
            typeSelect.appendChild(optElement);
        });

        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-param-btn';
        deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
        deleteBtn.addEventListener('click', () => {
            paramItem.remove();
        });

        paramItem.appendChild(nameInput);
        paramItem.appendChild(typeSelect);

        if (isInput) {
            const requiredCheckbox = document.createElement('div');
            requiredCheckbox.className = 'form-check';
            requiredCheckbox.innerHTML = `
                <input class="form-check-input param-required" type="checkbox" ${required ? 'checked' : ''}>
                <label class="form-check-label">必填</label>
            `;
            paramItem.appendChild(requiredCheckbox);
        }

        paramItem.appendChild(deleteBtn);

        return paramItem;
    }

    // 创建工具项
    function createToolItem(name = '', description = '') {
        const toolItem = document.createElement('div');
        toolItem.className = 'tool-item';

        const nameInput = document.createElement('input');
        nameInput.type = 'text';
        nameInput.className = 'form-control tool-name';
        nameInput.placeholder = '工具名称';
        nameInput.value = name;

        const descInput = document.createElement('input');
        descInput.type = 'text';
        descInput.className = 'form-control tool-description';
        descInput.placeholder = '工具描述';
        descInput.value = description;

        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-tool-btn';
        deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
        deleteBtn.addEventListener('click', () => {
            toolItem.remove();
        });

        toolItem.appendChild(nameInput);
        toolItem.appendChild(descInput);
        toolItem.appendChild(deleteBtn);

        return toolItem;
    }

    // 添加保存和加载功能
    window.saveFlowChart = () => {
        const data = flowChart.toJSON();
        const json = JSON.stringify(data, null, 2);
        const blob = new Blob([json], { type: 'application/json' });
        const url = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = 'flowchart.json';
        a.click();

        URL.revokeObjectURL(url);
    };

    window.loadFlowChart = (file) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            const data = JSON.parse(e.target.result);
            flowChart.loadFromJSON(data);
        };
        reader.readAsText(file);
    };

    // 初始化画布控制按钮
    function initializeCanvasControls() {
        const pointerBtn = document.querySelector('.control-btn.pointer');
        const handBtn = document.querySelector('.control-btn.hand');
        const zoomInBtn = document.querySelector('.control-btn.zoom-in');
        const zoomOutBtn = document.querySelector('.control-btn.zoom-out');
        const zoomFitBtn = document.querySelector('.control-btn.zoom-fit');
        const zoomLockBtn = document.querySelector('.control-btn.zoom-lock');

        // 确保所有需要的控制按钮存在
        if (!pointerBtn || !handBtn) {
            console.warn('交互模式按钮不存在，无法初始化画布控制');
            return;
        }

        // 默认设置为指针模式
        canvas.classList.add('pointer');
        flowChart.interactionMode = 'pointer';
        pointerBtn.classList.add('active');

        // 指针模式按钮
        pointerBtn.addEventListener('click', () => {
            canvas.classList.remove('hand');
            canvas.classList.add('pointer');
            flowChart.interactionMode = 'pointer';

            // 更新按钮状态
            handBtn.classList.remove('active');
            pointerBtn.classList.add('active');
        });

        // 手模式按钮
        handBtn.addEventListener('click', () => {
            canvas.classList.remove('pointer');
            canvas.classList.add('hand');
            flowChart.interactionMode = 'hand';

            // 更新按钮状态
            pointerBtn.classList.remove('active');
            handBtn.classList.add('active');
        });

        // 缩放按钮事件
        if (zoomInBtn) {
            zoomInBtn.addEventListener('click', () => {
                flowChart.zoomIn();
            });
        }

        if (zoomOutBtn) {
            zoomOutBtn.addEventListener('click', () => {
                flowChart.zoomOut();
            });
        }

        if (zoomFitBtn) {
            zoomFitBtn.addEventListener('click', () => {
                flowChart.zoomToFit();
            });
        }

        if (zoomLockBtn) {
            zoomLockBtn.addEventListener('click', () => {
                flowChart.toggleZoomLock();
                zoomLockBtn.classList.toggle('active');

                // 更新图标
                const icon = zoomLockBtn.querySelector('i');
                if (icon) {
                    if (flowChart.isZoomLocked) {
                        icon.className = 'fas fa-lock';
                    } else {
                        icon.className = 'fas fa-lock-open';
                    }
                }
            });
        }
    }
}); 